import Taro, { useDidShow, useRouter } from "@tarojs/taro";
import { Text, View } from "@tarojs/components";

import ByRow from "@/components/ui/ByRow";
import ByText from "@/components/ui/ByText";
import ByCell from "@/components/ui/ByCell";
import Page from "@/components/common/Page";
import ByButton from "@/components/ui/ByButton";
import ByCellGroup from "@/components/ui/ByCellGroup";
import QuestionDetail from "@/packageProject/components/QuestionDetail";

import ApiApp from "@/api/app";
import ApiAcceptance from "@/api/acceptance";
import useFetch from "@/hooks/useFetch";
import { objectToQueryString } from "@/utils";
import setting from "@/utils/setting";
import { IntentCustomerData } from "@/types/customer";
import ApiCrm from "@/api/crm";

type Result = {
  createDate: string;
  createUser: string;
  customerConfirmDate: string;
  customerConfirmPic: string[];
  nextAcceptDate: string;
  list: any[];
};

export default () => {
  const { params } = useRouter();
  const intentCustomerId = Number(params.intentCustomerId);
  const quesNaireId = Number(params.quesNaireId);
  const recordMainId = Number(params.recordMainId);
  const quesNaireType = decodeURIComponent(params.quesNaireType || "");



  // 客户信息
  const { data: customerData } = useFetch<IntentCustomerData>(ApiCrm.customerDetail, {
    defaultParams: [{ intentCustomerId }],
    onAfter: (res: any) => res.intentCustomer,
  });

  const { data, run } = useFetch<Result>(
    ApiAcceptance.acceptanceDetail,
    "POST",
    { manual: true }
  );

  useDidShow(() => {
    run(recordMainId ? { recordMainId } : { quesNaireId });
  });

  /**
   *  // 这两个都是临时性带过来的，应该已data数据为准，目前没有返回
   * state 0-已保存|1-已完成 (1已通过 0 未通过) 99 待验收
   * confirmStatius: 0-未确认|1-已确认
   */
  const { state, confirmStatius } = {
    state: Number(params.state),
    confirmStatius: Number(params.confirmStatius),
    ...data,
  };

  // 结果：未通过
  // const isNonPass = confirmStatius === 1 && state == 0;
  // const isNonPass = !data?.customerConfirmDate;

  // 待客户确认
  const customerConfirm = state === 1 && confirmStatius === 0;

  const { loading, run: getEncryptId } = useFetch(ApiApp.getEncryptId, {
    manual: true,
    async onSuccess(res: any) {
      const url = `${setting.webUrl
        }/customer/acceptance/${recordMainId}?encryptToken=${encodeURIComponent(
          res.encryptId
        )}`;

      const { confirm } = await Taro.showModal({
        title: "复制分享地址",
        content: "链接有效期3天，可将地址粘贴给客户",
        confirmText: "复制地址",
      });

      if (confirm) {
        Taro.setClipboardData({ data: `${customerData?.customerName}-${quesNaireType}-红杉树装饰：${url}` });
      }
    },
  });

  return (
    <>
      <Page
        footerSticky
        slotFooter={
          <ByRow content="around">
            {/* {customerConfirm && ( */}
            <ByButton
              size="large"
              className="w-1/3"
              loading={loading}
              type="primary"
              onClick={() => getEncryptId({ encryptId: recordMainId })}
            >
              客户验收
            </ByButton>
            {/* )} */}

            <ByButton
              size="large"
              className="w-1/3"
              loading={loading}
              type="warning"
              to={`form?${objectToQueryString({
                intentCustomerId,
                quesNaireId,
              })}`}
            >
              重新验收
            </ByButton>
          </ByRow>
        }
      >
        <View className="p-3 mb-4 bg-white text-sm">
          {data?.customerConfirmDate && (
            <ByRow className="mb-2" content="between">
              <ByText type="success">客户已验收</ByText>
              <Text className="text-sm">{data?.customerConfirmDate}</Text>
            </ByRow>
          )}

          <View className="text-sm text-second">
            <ByCell size="small" label="创建人">
              {data?.createUser}
            </ByCell>
            <ByCell size="small" label="创建时间">
              {data?.createDate}
            </ByCell>
            <ByCell size="small" label="下次验收">
              {data?.nextAcceptDate || "-"}
            </ByCell>
          </View>
        </View>

        {data?.list.map((item) => (
          <ByCellGroup
            key={item.quesNaireId}
            title={item.quesNaireName}
            className="m-3"
          >
            {item?.quesNaireContent.map((subItem, subIndex) => (
              <QuestionDetail
                source={subItem}
                key={subItem.quesId}
                index={subIndex + 1}
              />
            ))}
          </ByCellGroup>
        ))}
      </Page>
    </>
  );
};
